package cn.ffcs.uec.reportParameter.component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFCellUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.zkoss.web.servlet.Servlets;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.ListModel;

import cn.ffcs.raptornuke.portal.kernel.xml.DocumentException;
import cn.ffcs.uec.reportParameter.component.bean.ReportCollectionExtBean;
import cn.ffcs.uec.reportParameter.manager.VAllStaffZaiZhiManager;
import cn.ffcs.uec.reportParameter.model.VAllStaffZaiZhi;
import cn.ffcs.uec.reportParameter.model.VSexCount;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.vo.PageInfo;
import lombok.Getter;
import lombok.Setter;

public class ReportCollectionExt extends Div implements IdSpace {
	private static final long serialVersionUID = -139335897781983790L;
	private String url="/pages_nmg/reportcollection/comp/vallStaffZaiZhi_listbox_ext.zul";
	 private ReportCollectionExtBean bean = new ReportCollectionExtBean();
	private VAllStaffZaiZhiManager uecStaffAllManager = (VAllStaffZaiZhiManager) ApplicationContextUtil
			.getBean("vAllStaffZaiZhiManager");
	private String type="";
	
	//实体类
	private VSexCount vSexCount = new VSexCount();
	private VAllStaffZaiZhi vAllStaffZaiZhi = new VAllStaffZaiZhi();
	private List<VSexCount> sexList = null;
	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public ReportCollectionExt() {
		Executions.createComponents(this.url, this, null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');
	}
	/**
     * 界面初始化
     */
    public void onCreate() {
    	onQueryStaffTotalInfo();
    }

    /**
     * 查询员工信息
     * 
     * @throws Exception
     *             异常
     */
    public void onQueryStaffTotalInfo() {
        int activePage = bean.getAllStaffZaiZhiListboxPaging().getActivePage();
        int pageSize = bean.getAllStaffZaiZhiListboxPaging().getPageSize();
        PageInfo pageInfo = uecStaffAllManager.queryPageInfo(vAllStaffZaiZhi, activePage + 1,
                pageSize);
        if(pageInfo !=null ) {
	        ListModel list = new BindingListModelList(pageInfo.getDataList(), true);
	        //logDOwnList=logDownManager.getLogDownListAll(uecStaffAll, type);
	        this.bean.getVAllStaffZaiZhiListboxs().setModel(list);
	        this.bean.getAllStaffZaiZhiListboxPaging().setTotalSize(pageInfo.getTotalCount());
        }
    }

    /**
     * 每页显示事件
     */
    public void onPageSizeSelect() {
        if (this.bean.getPageListbox() != null && this.bean.getPageListbox().getSelectedItem().getValue() != null) {
            this.bean.getAllStaffZaiZhiListboxPaging().setActivePage(0);
            this.bean.getAllStaffZaiZhiListboxPaging()
                    .setPageSize(Integer.parseInt(this.bean.getPageListbox().getSelectedItem().getValue().toString()));
        }
        this.onQueryStaffTotalInfo();
    }

    /**
     * 翻页
     */
    public void onAllStaffZaiZhiListboxPaging() {
        onQueryStaffTotalInfo();
    }
    
    /**
     * 查询按钮
     * @throws Exception
     * @throws InterruptedException
     */
    public void onReportParametr() throws Exception, InterruptedException {
    	vAllStaffZaiZhi = new VAllStaffZaiZhi();
    	//uecStaffAll.setCode(!StrUtil.isNullOrEmpty(bean.getStaffCode().getValue())?bean.getStaffCode().getValue():""); 
        //uecStaffAll.setName(!StrUtil.isNullOrEmpty(bean.getStaffName().getValue())?bean.getStaffName().getValue():"");
        this.onQueryStaffTotalInfo();
    }

    /**
     * 重置按钮
     */
    public void onReset() {
        clearVariable();
        ListboxUtils.clearListbox(this.bean.getVAllStaffZaiZhiListboxs());
        this.bean.getAllStaffZaiZhiListboxPaging().setTotalSize(1);
        vAllStaffZaiZhi = new VAllStaffZaiZhi();
    }

    /**
     * 清除变量
     */
    public void clearVariable() {
    	vAllStaffZaiZhi = null;
    }
	
	
	
	
	
	/**
	 * @throws Exception 
	 * @throws ParseException 
	 * @throws InterruptedException
	 *             报表导出按钮，通过按钮触发
	 * @Title: onOk
	 * @Description: TODO
	 * @param:
	 * @return: void
	 * @throws
	 */
	public void onOk() throws Exception {
		try {
			String charset = "UTF-8";
            // 图片名称
            String fileName = "按性别统计报表";
            // 编码后文件名
            String encodedName = null;
            encodedName = URLEncoder.encode(fileName, charset);
            byte[] bsPdf = exportExcel();
            // 将空格替换为+号
            encodedName = encodedName.replace("%20", "+");
            HttpServletRequest httpRequest = (HttpServletRequest) Executions.getCurrent()
                    .getNativeRequest();
            // 解决ie6 bug 或者是火狐浏览器
            if (encodedName.length() > 150 || Servlets.isGecko(httpRequest)
                    || Servlets.isGecko3(httpRequest)) {
                encodedName = new String(fileName.getBytes(charset), "ISO8859-1");
            }
			Filedownload.save(bsPdf, "application/vnd.ms-excel", fileName);
			//Events.postEvent("onOK", this.self, null);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (com.itextpdf.text.DocumentException e) {
			e.printStackTrace();
		}
	}
	

	/**
	 * @desc 生成EXCEL
	 * @return: byte[] 
	 * @throws DocumentException
	 * @throws IOException
	 * @throws com.itextpdf.text.DocumentException
	 * @throws ParseException 
	 * @throws InterruptedException
	 */
	@SuppressWarnings("resource")
	public byte[] exportExcel() throws Exception {  
		//数据来源
		 sexList = uecStaffAllManager.getSexList(vSexCount);
		
		HSSFWorkbook workbook = new HSSFWorkbook();
	    HSSFSheet sheet = workbook.createSheet("按性别统计报表");
	    //单元格标题格式(开始)
	    HSSFCellStyle cellStyle1 = workbook.createCellStyle();  //单元格标题
	    cellStyle1.setAlignment(HorizontalAlignment.CENTER);  
	    cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
	    cellStyle1.setWrapText(false);//自动换行
	    cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);//下边框
	    cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
	    cellStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
	    cellStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
	    HSSFFont fonttitle = workbook.createFont();  
	    fonttitle.setColor(HSSFColor.BLACK.index);  
	    fonttitle.setBold(false);
	   // fonttitle.setFontHeightInPoints((short) 16);;
	    cellStyle1.setFont(fonttitle);
	    //单元格标题格式（结束）
        
        //单元格正文内容格式(开始)
        HSSFCellStyle cellStyle2 = workbook.createCellStyle();  //单元格标题
        cellStyle2.setAlignment(HorizontalAlignment.CENTER);  
        cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle2.setWrapText(false);//自动换行
        HSSFFont font2 = workbook.createFont();  
        font2.setColor(HSSFColor.BLACK.index);  
        cellStyle2.setFont(font2);
        cellStyle2.setBorderBottom(HSSFCellStyle.BORDER_THIN);//下边框
        cellStyle2.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        cellStyle2.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        cellStyle2.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        //单元格正文格式（结束）
	    // 将第一行的8个单元格给合并
	   // sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
	    HSSFRow row = sheet.createRow(0);
	    HSSFCell beginCell = row.createCell(0);
	    beginCell.setCellValue("上级组织名称");  
	    row.createCell(1).setCellValue("公司名称");
	    row.createCell(2).setCellValue("性别");
        row.createCell(3).setCellValue("");
     // 将第一行的8个单元格给合并
	   // beginCell.setCellStyle(cellStyle1);
	    sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 3));
	    sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
	    sheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1));
	   // setRegionStyle(sheet,new CellRangeAddress(0, 0, 2, 3),cellStyle2);
	    setBorderStyle(row,cellStyle1);
	    row = sheet.createRow(1);    
	    row.createCell(0).setCellValue(""); 
	    row.createCell(1).setCellValue(""); 
	    row.createCell(2).setCellValue("男"); 
	    HSSFCell createCell = row.createCell(3);
	    createCell.setCellValue("女"); 
	    createCell.setCellStyle(cellStyle1);
	    setBorderStyle(row,cellStyle1);
	    if(sexList != null && sexList.size()>0) {
	    	for (int i = 0; i < sexList.size(); i++) {
	    		 row = sheet.createRow(2+i); 
	    		 row.createCell(0).setCellValue(sexList.get(i).getForgname()); 
	    		 row.createCell(1).setCellValue(sexList.get(i).getOrgname()); 
	    		 row.createCell(2).setCellValue(sexList.get(i).getMencount()); 
	    		 HSSFCell createCell1 = row.createCell(3);
	    		 createCell1.setCellValue(sexList.get(i).getWomencount()); 
	    		 createCell1.setCellStyle(cellStyle2);
	    		 setBorderStyle(row,cellStyle2);
			}
	    }
	   
	    //到这里，excel就已经生成了，然后就需要通过流来写出去
	    sheet.setDefaultColumnWidth(10);//设置列宽
	    sheet.setDefaultRowHeight((short)8);
	    /*sheet.setHorizontallyCenter(true);
	    sheet.setVerticallyCenter(true);
	    sheet.setPrintGridlines(true);
	    sheet.setMargin((short)2, 2);
	    sheet.setDisplayGridlines(true);*/
	    /**
		 * 通过浏览器下载
		 */
	   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	    workbook.write(byteArrayOutputStream);
	  //将流写进response输出流中
		if (byteArrayOutputStream != null) {
			byte[] bs = byteArrayOutputStream.toByteArray();
			byteArrayOutputStream.close();
			return bs;
		}
		return null;
	}
	
	/**
	 * 给标题单元格设置格式
	 * @param strList   单元格内容，字符串数组
	 * @param sheet     
	 * @param rowIndex   定义行索引，从0开始，需要手工输入
	 * @param cellStyle  单元格样式
	 * @return
	 */
	public void setBorderStyle(HSSFRow row,HSSFCellStyle cellStyle) {
	      row.getCell(0).setCellStyle(cellStyle);
			for (int i = row.getFirstCellNum(); i < row.getLastCellNum()-1; i++) {
				 row.getCell(i).setCellStyle(cellStyle);
				 
		}
		//return row;
	}
	public static void setRegionStyle(HSSFSheet sheet, CellRangeAddress region,
            HSSFCellStyle cs) {
        for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
            HSSFRow row = HSSFCellUtil.getRow(i, sheet);
            HSSFCell cell = null;
            //循环设置单元格样式
            for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
                cell = HSSFCellUtil.getCell(row, (short) j);
                cell.setCellStyle(cs);
            }
         //   System.out.println("r2==========="+i);
        }
        
    }
}
